



#include "asio.hpp"
#include "server.h"

#include <boost/smart_ptr.hpp>
#include <boost/bind.hpp>
#include "ServerConn.h"



struct Server::Impl{
    asio::io_service _ios;
    asio::ip::tcp::acceptor _acceptor;
    public:
    Impl():_acceptor(_ios, asio::ip::tcp::endpoint( asio::ip::tcp::v4(), 8000) ){
    }

    void start_accept()
    {
        //printf("init4\n");
        ServerConn::pointer new_connection = ServerConn::create( _ios);
        //printf("init5\n");

        _acceptor.async_accept(new_connection->socket(),
                boost::bind(&Server::Impl::handle_accept, this, new_connection,
                    asio::placeholders::error));
        //printf("init6\n");
    }
    void handle_accept(ServerConn::pointer new_connection, const asio::error_code& error)
    {
        if (!error)
        {
            new_connection->start();
            printf("created a new connection!\n");
            start_accept();
        }
    }
};


static void print(const asio::error_code& err , int *count){
    printf( "%d" , *count);
}

Server::Server():_impl( new Impl() ){
}

Server::~Server(){
    delete _impl;
}

void Server::init(){

    //printf("init1\n");
    _impl->start_accept();
    //printf("init2\n");
    _impl->_ios.run();
    //printf("init3\n");

}




#ifdef UNIT_TEST
int main( int argc, char* argv[]){

    Server svr;
    svr.init();


    return 0;

}
#endif //UNIT_TEST
